package com.java.business.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.java.business.dao.PurchaseBillMapper;
import com.java.business.model.PurchaseBill;
import com.java.business.service.PurchaseBillService;
import com.java.common.model.Result;
import com.java.common.util.JwtUtil;
import com.java.manage.model.Company;
import com.java.manage.service.api.CompanyApiService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class PurchaseBillServiceImpl implements PurchaseBillService {

    @Autowired
    private PurchaseBillMapper purchaseBillMapper;

    @DubboReference
    private CompanyApiService companyApiService;

    @Autowired
    private HttpServletRequest request;

    @Override
    public Result list(PurchaseBill purchaseBill) {
        PageHelper.startPage(purchaseBill.getPageNum(), purchaseBill.getPageSize()); // 提醒page在显示哪一页的数据和要显示多少条数据

        String token = request.getHeader("Token");
        Integer storeId = (Integer) JwtUtil.getClaims(token).get("storeId");
        purchaseBill.setStoreId(storeId);

        List<PurchaseBill> list = purchaseBillMapper.list(purchaseBill);

        // 查询关联的公司信息
        List<Integer> collect = list.stream().map(PurchaseBill::getStoreId).collect(Collectors.toList());
        List<Company> companies = companyApiService.listByIds(collect);
        Map<Integer, Company> companyMap = companies.stream().collect(Collectors.toMap(company -> company.getId(), company -> company));


        list.stream().forEach(bor -> {
            bor.setCompany(companyMap.get(bor.getStoreId()));
        });

        PageInfo<PurchaseBill> pageInfo = new PageInfo<>(list);

        Map<String, Object> map = new HashMap<>();
        map.put("list", pageInfo.getList());
        map.put("total", pageInfo.getTotal());

        return Result.success(map);
    }

    @Override
    public Result save(PurchaseBill purchaseBill) {
        purchaseBillMapper.save(purchaseBill);
        return Result.success();
    }

    @Override
    public Result modify(PurchaseBill purchaseBill) {
        purchaseBillMapper.modify(purchaseBill);
        return Result.success();
    }

    @Override
    public Result remove(int[] ids) {
        for (int id : ids) {
            purchaseBillMapper.remove(id);
        }
        return Result.success();
    }

    @Override
    public Result get(int id) {
        purchaseBillMapper.get(id);
        return Result.success();
    }

//    @Override
//    public Result companyList(Company company) {
//        purchaseBillMapper.companyList(company);
//        return Result.success();
//    }
}
